package com.atguigu.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;


@Configuration
@EnableWebSecurity //@EnableWebSecurity是开启SpringSecurity的默认行为
//开启给予方法级别细粒度权限控制。即，在controller方法上架权限注解即可，例如@PreAuthorize("hasAuthority('role.show')")
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    UserDetailsService userDetailsService;

    /*认证：
        1.基于内存的认证方式（了解）
        2.基于数据库的认证方式（重点）
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //1.基于内存的认证，写死用户名称和密码，分配空的角色既无任何权限
//        auth.inMemoryAuthentication()
//                .withUser("lucy")
//                .password(new BCryptPasswordEncoder().encode("123456"))
//                .roles("");
        //2.基于数据库的认证方式
        auth.userDetailsService(userDetailsService);
    }



    /**
     * 声明Bean对象  等价于<bean id="PasswordEncoder" class="xxx"></>
     * 必须指定加密方式，上下加密方式要一致
     */
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    /**
     * 授权：
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //默认授权，不登录系统，所有资源都不允许访问
//        super.configure(http);
        //自定义权限控制
        //1.，设置同源允许访问
        http.headers().frameOptions().sameOrigin();//同源的资源允许访问

        //2.授权静态资源不登录允许访问
        http.authorizeRequests().antMatchers("/static/**", "/login").permitAll()
                .anyRequest().authenticated();
        //3.授权自定义的登录页面
        //loginPage（）表示通过映射，跳转到自己的登录业
        //defaultSuccessUrl（）登录成功后去哪里
        http.formLogin().loginPage("/login").defaultSuccessUrl("/");
        //4.授权注销路径
        http.logout().logoutUrl("/logout").logoutSuccessUrl("/login");

        //5.关闭跨站请求伪造功能
        //<input type="hidden" name="_csrf" value="c058a5fb-9db7-4abf-92ed-8fbad3f1c241"/>
        http.csrf().disable();//登录时，就没有隐藏域了
        //6.添加自定义异常入口

        http.exceptionHandling().accessDeniedHandler(new CustomAccessDeniedHandler());
    }
}
